<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="结网之路" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本章主要讲了如何使用 android 系统的网络连接，并介绍了格式化 JSON 和多线程编程 AsyncTask 的使用。另外，挑战练习里还结合了 Gson 库的使用。
GitHub 地址：完成23章但未完成挑战完成23章挑战1：使用 Gson完成23章挑战2：添加分页完成23章挑战3：动态调整网格列

1. 网络连接基本首先要在 Manifest 文件中请求网络权限
1&amp;lt;uses-per">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第二版）学习笔记（二十三）—— 第23章 HTTP 与后台任务">
<meta property="og:url" content="https://kniost.github.io/2017-02-11-cj0ag5y6s001nifs6ztgicoai/index.html">
<meta property="og:site_name" content="结网之路">
<meta property="og:description" content="本章主要讲了如何使用 android 系统的网络连接，并介绍了格式化 JSON 和多线程编程 AsyncTask 的使用。另外，挑战练习里还结合了 Gson 库的使用。
GitHub 地址：完成23章但未完成挑战完成23章挑战1：使用 Gson完成23章挑战2：添加分页完成23章挑战3：动态调整网格列

1. 网络连接基本首先要在 Manifest 文件中请求网络权限
1&amp;lt;uses-per">
<meta property="og:updated_time" content="2017-03-14T07:09:47.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第二版）学习笔记（二十三）—— 第23章 HTTP 与后台任务">
<meta name="twitter:description" content="本章主要讲了如何使用 android 系统的网络连接，并介绍了格式化 JSON 和多线程编程 AsyncTask 的使用。另外，挑战练习里还结合了 Gson 库的使用。
GitHub 地址：完成23章但未完成挑战完成23章挑战1：使用 Gson完成23章挑战2：添加分页完成23章挑战3：动态调整网格列

1. 网络连接基本首先要在 Manifest 文件中请求网络权限
1&amp;lt;uses-per">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kniost.github.io/2017-02-11-cj0ag5y6s001nifs6ztgicoai/"/>





  <title> Android编程权威指南（第二版）学习笔记（二十三）—— 第23章 HTTP 与后台任务 | 结网之路 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">结网之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">临渊羡鱼，不如退而结网</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kniost.github.io/2017-02-11-cj0ag5y6s001nifs6ztgicoai/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kniost">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="结网之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android编程权威指南（第二版）学习笔记（二十三）—— 第23章 HTTP 与后台任务
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-02-11T17:21:10+08:00">
                2017-02-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android编程权威指南学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">Android编程权威指南学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017-02-11-cj0ag5y6s001nifs6ztgicoai/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017-02-11-cj0ag5y6s001nifs6ztgicoai/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本章主要讲了如何使用 android 系统的网络连接，并介绍了格式化 JSON 和多线程编程 AsyncTask 的使用。另外，挑战练习里还结合了 Gson 库的使用。</p>
<p>GitHub 地址：<br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/62310fed3abea3bb08151656539dffbf035a69f6" target="_blank" rel="external">完成23章但未完成挑战</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/4e47fb20d3285fe7cc61ccce140f467c5935a6d3" target="_blank" rel="external">完成23章挑战1：使用 Gson</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/5445c65491e29e2a6fd349667c8621b4bed903e6" target="_blank" rel="external">完成23章挑战2：添加分页</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/074e528d9160a82d9881e184f7132a1a8fa67b34" target="_blank" rel="external">完成23章挑战3：动态调整网格列</a></p>
</blockquote>
<h1 id="1-网络连接基本"><a href="#1-网络连接基本" class="headerlink" title="1. 网络连接基本"></a>1. 网络连接基本</h1><p>首先要在 Manifest 文件中请求网络权限</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.INTERNET"</span> /&gt;</span></div></pre></td></tr></table></figure>
<p>然后我们建立一个网络请求的函数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// FlickrFetchr.java</span></div><div class="line"><span class="comment">// 参数是 url 字符串，并且需要抛出 IO 错误</span></div><div class="line"><span class="keyword">public</span> <span class="keyword">byte</span>[] getUrlBytes(String urlSpec) <span class="keyword">throws</span> IOException &#123;</div><div class="line">    URL url = <span class="keyword">new</span> URL(urlSpec);</div><div class="line">    <span class="comment">// 打开连接</span></div><div class="line">    HttpURLConnection connection = (HttpURLConnection) url.openConnection();</div><div class="line"></div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">    	<span class="comment">// 建立两个流对象</span></div><div class="line">        ByteArrayOutputStream out = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">        <span class="comment">// 使用 getInputStream() 方法时才会真正发送 GET 请求</span></div><div class="line">        <span class="comment">// 如果要使用 POST 请求，需要调用 getOutputStream()</span></div><div class="line">        InputStream in = connection.getInputStream();</div><div class="line">		<span class="comment">// 如果连接失败就抛出错误</span></div><div class="line">        <span class="keyword">if</span> (connection.getResponseCode() != HttpURLConnection.HTTP_OK) &#123;</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IOException(connection.getResponseMessage() +</div><div class="line">                    <span class="string">": with"</span> +</div><div class="line">                    urlSpec);</div><div class="line">        &#125;</div><div class="line">        </div><div class="line">        <span class="comment">// 建立一个计数器</span></div><div class="line">        <span class="keyword">int</span> bytesRead = <span class="number">0</span>;</div><div class="line">        <span class="comment">// 建立一个缓存 buffer</span></div><div class="line">        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</div><div class="line">        <span class="comment">// 用 InputStream.read 将数据读取到 buffer 中，</span></div><div class="line">        <span class="comment">// 然后写到 OutputStream 中</span></div><div class="line">        <span class="keyword">while</span> ((bytesRead = in.read(buffer)) &gt; <span class="number">0</span>) &#123;</div><div class="line">            out.write(buffer, <span class="number">0</span>, bytesRead);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 之后一定要关闭 OutputStream</span></div><div class="line">        out.close();</div><div class="line">        <span class="keyword">return</span> out.toByteArray();</div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">    	<span class="comment">// 最后要关闭连接</span></div><div class="line">        connection.disconnect();</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getUrlString</span><span class="params">(String urlSpec)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">	<span class="comment">// 将结果转换成 String</span></div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> String(getUrlBytes(urlSpec));</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="2-线程与主线程"><a href="#2-线程与主线程" class="headerlink" title="2. 线程与主线程"></a>2. 线程与主线程</h1><p>网络连接需要时间，Web 服务器可能需要1~2秒的时间来响应访问请求，文件下载则耗时更久。考虑到这个因素，Android 禁止任何主线程网络连接行为。即使强行在主线程中进行网络连接，Android 也会抛出 NetworkOnMainThreadException 异常。</p>
<p>这是为什么呢?要想知道，首先要了解什么是线程，什么是主线程以及主线程的用途是什么。<br><strong>线程是个单一执行序列。单个线程中的代码会逐步执行。所有 Android 应用的运行都是从主线程开始的。然而，主线程不是线程那样的预定执行序列。相反，它处于一个无限循环的运行状态，等待着用户或系统触发事件的发生。事件触发后，主线程便负责执行代码，以响应这些事件。</strong></p>
<p>主线程运行着所有更新 UI 的代码，其中包括响应 activity 的启动、按钮的点击等不同 UI 相关事件的代码。(由于响应的事件基本都与用户界面相关，主线程有时也叫作 UI 线程。)<br>事件处理循环让 UI 代码得以按顺序执行。这可以保证任何事件处理都不会发生冲突，同时代码也能够快速响应执行。</p>
<p>而网络连接相比其他任务更耗时。等待响应期间，用户界面毫无反应，这可能会导致应用无响应(Application Not Responding,ANR)现象发生，也就是一个弹框，要求你关闭应用。<br>怎样使用后台线程最容易呢？答案就是使用 AsyncTask 类</p>
<h1 id="3-AsyncTask"><a href="#3-AsyncTask" class="headerlink" title="3. AsyncTask"></a>3. AsyncTask</h1><h2 id="3-1-AsyncTask-的生命"><a href="#3-1-AsyncTask-的生命" class="headerlink" title="3.1 AsyncTask 的生命"></a>3.1 AsyncTask 的生命</h2><p>AsyncTask 类可以重写的方法和一个进程的生命过程对应：</p>
<ul>
<li><code>onPreExecute()</code> 执行之前</li>
<li><code>onProgressUpdate()</code> 更新进展</li>
<li><code>doInBackground()</code> 在线程中真正要完成的事</li>
<li><code>onPostExecute()</code> 完成之后要做的事（在 UI 线程中执行）</li>
<li><code>onCancelled()</code>    退出之后</li>
</ul>
<h2 id="3-2-AsyncTask-的三个参数"><a href="#3-2-AsyncTask-的三个参数" class="headerlink" title="3.2 AsyncTask 的三个参数"></a>3.2 AsyncTask 的三个参数</h2><p>其中模板的三个类类型参数（不能是基础类型）分别是：输入、进度、结果。</p>
<h3 id="3-2-1-第一个参数：输入"><a href="#3-2-1-第一个参数：输入" class="headerlink" title="3.2.1 第一个参数：输入"></a>3.2.1 第一个参数：输入</h3><p>第一个类型参数可指定输入参数的类型。可参考以下示例使用该参数:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">AsyncTask&lt;String,Void,Void&gt; task = <span class="keyword">new</span> AsyncTask&lt;String,Void,Void&gt;() &#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> Void <span class="title">doInBackground</span><span class="params">(String... params)</span> </span>&#123; </div><div class="line">		<span class="keyword">for</span> (String parameter : params) &#123;</div><div class="line">			Log.i(TAG, <span class="string">"Received parameter: "</span> + parameter);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">	&#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>输入参数传入 execute(…)方法(可接受一个或多个参数): task.execute(“第一个参数”, “第二个参数”, “……”);<br>然后，再把这些变量参数传递给 doInBackground(…)方法。 </p>
<h3 id="3-2-2-第二个参数：进度"><a href="#3-2-2-第二个参数：进度" class="headerlink" title="3.2.2 第二个参数：进度"></a>3.2.2 第二个参数：进度</h3><p>第二个类型参数可指定发送进度更新需要的类型。以下为示例代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">final</span> ProgressBar gestationProgressBar = <span class="comment">/* 一个特定的进度条 */</span>;</div><div class="line">gestationProgressBar.setMax(<span class="number">42</span>); <span class="comment">/* 最大的进度 */</span></div><div class="line">AsyncTask&lt;Void,Integer,Void&gt; haveABaby = <span class="keyword">new</span> AsyncTask&lt;Void,Integer,Void&gt;() &#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> Void <span class="title">doInBackground</span><span class="params">(Void... params)</span> </span>&#123;</div><div class="line">		<span class="keyword">while</span> (!babyIsBorn()) &#123;</div><div class="line">			Integer weeksPassed = getNumberOfWeeksPassed();</div><div class="line">          publishProgress(weeksPassed); <span class="comment">// 关键，将参数发送到 onProgressUpdate</span></div><div class="line">          patientlyWaitForBaby();</div><div class="line">		&#125; </div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onProgressUpdate</span><span class="params">(Integer... params)</span> </span>&#123;</div><div class="line">		<span class="keyword">int</span> progress = params[<span class="number">0</span>];</div><div class="line">		gestationProgressBar.setProgress(progress);</div><div class="line">	&#125; </div><div class="line">&#125;;</div><div class="line"><span class="comment">/* call when you want to execute the AsyncTask */</span></div><div class="line">haveABaby.execute();</div></pre></td></tr></table></figure>
<p>进度更新通常发生在执行的后台进程中。问题是，在后台进程中无法完成必要的 UI 更新。因此 AsyncTask 提供了 publishProgress(…)和 onProgressUpdate(…)方法。<br> 其工作方式是这样的 : 在后台线程中 , 从 doInBackground(…) 方法中调用 publishProgress(…)方法。这样 onProgressUpdate(…)方法便能够在 UI 线程上调用。因此，在 onProgressUpdate(…)方法中执行 UI 更新就可行了，但必须在 doInBackground(…) 方法中使用 publishProgress(…)方法对它们进行管控。</p>
<h3 id="3-2-3-第三个参数：结果"><a href="#3-2-3-第三个参数：结果" class="headerlink" title="3.2.3 第三个参数：结果"></a>3.2.3 第三个参数：结果</h3><p>第三个类型参数是处理结果返回的类型参数。下面是本章的示例代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// PhotoGalleryFragment.java</span></div><div class="line"></div><div class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">FetchItemsTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">Integer</span>, <span class="title">Void</span>, <span class="title">List</span>&lt;<span class="title">GalleryItem</span>&gt;&gt; </span>&#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> List&lt;GalleryItem&gt; <span class="title">doInBackground</span><span class="params">(Integer... params)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> FlickrFetchr().fetchItems(params[<span class="number">0</span>]);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPostExecute</span><span class="params">(List&lt;GalleryItem&gt; galleryItems)</span> </span>&#123;</div><div class="line">        mItems = galleryItems;</div><div class="line">        setAdapter();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>第三个参数就是在 doInBackground 中返回的结果，我们需要从后台请求 API 返回的 JSON 数据，然后将其格式化，返回的就是我们需要的数据。</p>
<h1 id="4-JSON-数据解析"><a href="#4-JSON-数据解析" class="headerlink" title="4. JSON 数据解析"></a>4. JSON 数据解析</h1><p>什么是 JSON 数据呢？JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于 JavaScript 的一个子集。JSON 采用完全独立于语言的文本格式，但是也使用了类似于C语言家族的习惯（包括C, C++, C#, Java, JavaScript, Perl, Python 等）。这些特性使 JSON 成为理想的数据交换语言。</p>
<p>JSON 对象是一系列包含在{ }中的名值对。JSON 数组是包含在[ ]中用逗号隔开的 JSON 对象列表。对象彼此嵌套形成层级关系。详细的语法可以查看<a href="http://json.org/" target="_blank" rel="external">JSON 官网</a>。</p>
<p>JSON 这种数据格式在同样基于这些结构的编程语言之间交换十分方便，所以网络服务器端越来越多地开始用 JSON 来交换数据，我们在这章使用的 API 同样如此。</p>
<h2 id="一个例子"><a href="#一个例子" class="headerlink" title="一个例子"></a>一个例子</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 为节省版面，去掉了无关的属性</span></div><div class="line">&#123;</div><div class="line">  <span class="string">"photos"</span>: &#123;</div><div class="line">    <span class="string">"page"</span>: <span class="number">1</span>,</div><div class="line">    <span class="string">"pages"</span>: <span class="number">10</span>,</div><div class="line">    <span class="string">"photo"</span>: [</div><div class="line">      &#123;</div><div class="line">        <span class="string">"id"</span>: <span class="string">"31987348504"</span>,</div><div class="line">        <span class="string">"title"</span>: <span class="string">"Penny"</span>,</div><div class="line">        <span class="string">"url_s"</span>: <span class="string">"https://farm3.staticflickr.com/2915/31987348504_9a949c482d_m.jpg"</span>,</div><div class="line">      &#125;,</div><div class="line">      &#123;</div><div class="line">        <span class="string">"id"</span>: <span class="string">"31987352214"</span>,</div><div class="line">        <span class="string">"title"</span>: <span class="string">""</span>,</div><div class="line">        <span class="string">"url_s"</span>: <span class="string">"https://farm1.staticflickr.com/455/31987352214_58428f3a9d_m.jpg"</span>,</div><div class="line">      &#125;</div><div class="line">    ]</div><div class="line">  &#125;,</div><div class="line">  <span class="string">"stat"</span>: <span class="string">"ok"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>对应的解析代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 解析时用 try…catch，要抛出 JSONException 防止程序崩溃</span></div><div class="line"><span class="comment">// JSONObject 构造方法解析传入的 JSON 数据后</span></div><div class="line"><span class="comment">// 会生成与原始 JSON 数据对应的对象树</span></div><div class="line">JSONObject jsonBody = <span class="keyword">new</span> JSONObject(jsonString);</div><div class="line"></div><div class="line"><span class="comment">// 顶层 JSONObject 对应着原始数据最外层的&#123; &#125;。它包含了一个叫作 photos 的嵌套 JSONObject</span></div><div class="line">JSONObject photosJsonObject = jsonBody.getJSONObject(<span class="string">"photos"</span>);</div><div class="line"></div><div class="line"><span class="comment">// 这个嵌套对象又包含了一个叫作 photo 的 JSONArray</span></div><div class="line">JSONArray photoJsonArray = photosJsonObject.getJSONArray(<span class="string">"photo"</span>);</div><div class="line"></div><div class="line"><span class="comment">// 这个嵌套数组中又包含了一组 JSONObject</span></div><div class="line"><span class="comment">// 这些 JSONObeject 就是要获取的一张张图片的元数据</span></div><div class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; photoJsonArray.length(); i++) &#123;</div><div class="line">    JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);</div><div class="line">    GalleryItem item = <span class="keyword">new</span> GalleryItem();</div><div class="line">    item.setId(photoJsonObject.getString(<span class="string">"id"</span>));</div><div class="line">    item.setCaption(photoJsonObject.getString(<span class="string">"title"</span>));</div><div class="line">    <span class="keyword">if</span> (!photoJsonObject.has(<span class="string">"url_s"</span>)) &#123;</div><div class="line">        <span class="keyword">continue</span>;</div><div class="line">    &#125;</div><div class="line">    item.setUrl(photoJsonObject.getString(<span class="string">"url_s"</span>));</div><div class="line">    items.add(item);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>解析完成后就可以在 AsyncTask 的 onPostExecute 中对 UI 进行更新了。</p>
<h1 id="5-挑战练习"><a href="#5-挑战练习" class="headerlink" title="5. 挑战练习"></a>5. 挑战练习</h1><p>本章的挑战练习难度依次递增，考验了我们很多知识。</p>
<h2 id="5-1-使用-Gson-库解析-JSON-数据"><a href="#5-1-使用-Gson-库解析-JSON-数据" class="headerlink" title="5.1 使用 Gson 库解析 JSON 数据"></a>5.1 使用 Gson 库解析 JSON 数据</h2><p>Gson 是 Google 官方推荐的 JSON 解析库，使用 Gson 不用写任何解析代码，它能自动将 JSON 数据映射为 Java 对象。</p>
<h3 id="5-1-1-添加-Gson-依赖"><a href="#5-1-1-添加-Gson-依赖" class="headerlink" title="5.1.1 添加 Gson 依赖"></a>5.1.1 添加 Gson 依赖</h3><p>在 File -&gt; Project Structure -&gt; Dependencies 中添加 gson 依赖</p>
<h3 id="5-1-2-构建对应的-POJO-类"><a href="#5-1-2-构建对应的-POJO-类" class="headerlink" title="5.1.2 构建对应的 POJO 类"></a>5.1.2 构建对应的 POJO 类</h3><p>由于不想更改原本的 GalleryItem 类，并且想让成员变量的命名符合 java 的命名规范，我使用了 <code>@SerializedName()</code> 注解，这个注解注明了 Gson 在转换时对应的键名。并且构建了一个新的类，用于匹配对应的 API 结构：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// PhotoBean.java</span></div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoBean</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String STATUS_OK = <span class="string">"ok"</span></div><div class="line">            , STATUS_FAILED = <span class="string">"fail"</span>;</div><div class="line"></div><div class="line">    <span class="meta">@SerializedName</span>(<span class="string">"photos"</span>)</div><div class="line">    <span class="keyword">private</span> PhotosInfo mPhotoInfo;</div><div class="line">    <span class="meta">@SerializedName</span>(<span class="string">"stat"</span>)</div><div class="line">    <span class="keyword">private</span> String mStatus;</div><div class="line">    <span class="meta">@SerializedName</span>(<span class="string">"message"</span>)</div><div class="line">    <span class="keyword">private</span> String mMessage;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotosInfo</span> </span>&#123;</div><div class="line">        <span class="meta">@SerializedName</span>(<span class="string">"photo"</span>)</div><div class="line">        List&lt;GalleryItem&gt; mPhoto;</div><div class="line"></div><div class="line">        <span class="function"><span class="keyword">public</span> List&lt;GalleryItem&gt; <span class="title">getPhoto</span><span class="params">()</span> </span>&#123;</div><div class="line">            <span class="keyword">return</span> mPhoto;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">// 省略 getter 和 setter</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="5-1-3-使用-Gson"><a href="#5-1-3-使用-Gson" class="headerlink" title="5.1.3 使用 Gson"></a>5.1.3 使用 Gson</h3><p>Gson 的使用再简单不过了，与上面的代码相比有云泥之别：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">PhotoBean photoBean = (PhotoBean) <span class="keyword">new</span> Gson()</div><div class="line">        .fromJson(jsonString, PhotoBean.class);</div></pre></td></tr></table></figure>
<p>不过记得要抛出 JsonSyntaxException。</p>
<h2 id="5-2-分页显示"><a href="#5-2-分页显示" class="headerlink" title="5.2 分页显示"></a>5.2 分页显示</h2><p>这个挑战的需求是：如果我们下滑最底部，就在后面添加下一页的内容。<br>所以在 url 的生成中我们还要加入 page 这个参数。我加入了一个成员变量 mNextPage 用于记录下次要请求的页面， 然后添加了一个常量 MAX_PAGES 用于控制最大请求页数。</p>
<h3 id="5-2-1-RecyclerView-onScrollListener"><a href="#5-2-1-RecyclerView-onScrollListener" class="headerlink" title="5.2.1 RecyclerView.onScrollListener"></a>5.2.1 <code>RecyclerView.onScrollListener</code></h3><p>onScrollListener 有两个可以重写的方法，一个是 onScrollStateChanged()，还有一个是 onScrolled，对我们这个需求来说，显然 onScrollStateChanged 比较合适，ScrollState 也有三种：</p>
<ul>
<li><code>SCROLL_STATE_IDLE</code>: 视图没有被拖动，处于静止  </li>
<li><code>SCROLL_STATE_DRAGGING</code>： 视图正在拖动中 </li>
<li><code>SCROLL_STATE_SETTLING</code>： 视图在惯性滚动 </li>
</ul>
<p>这个挑战最关键的就是如何判断滑到最底端。首先滑动到最底端时前两个状态其实都可以，但是滑动到最底这个信息只有 LayoutManager 知道，我们可以直接看代码分析：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> RecyclerView.OnScrollListener onButtomListener = </div><div class="line">		<span class="keyword">new</span> RecyclerView.OnScrollListener() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScrollStateChanged</span><span class="params">(RecyclerView recyclerView, <span class="keyword">int</span> newState)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>.onScrollStateChanged(recyclerView, newState);</div><div class="line">        <span class="comment">// 首先获取 LayoutManager</span></div><div class="line">        GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();</div><div class="line">        <span class="comment">// 然后可以找到最后显示的位置，一旦滚动就会获取该位置</span></div><div class="line">        mLastPosition = layoutManager.findLastCompletelyVisibleItemPosition();</div><div class="line">        <span class="comment">// 如果静止的时候最后的位置大于等于数据个数</span></div><div class="line">        <span class="comment">// 而且前一个任务完成时（防止多次重复）</span></div><div class="line">        <span class="keyword">if</span> (newState == RecyclerView.SCROLL_STATE_IDLE</div><div class="line">                &amp;&amp; mLastPosition &gt;= mPhotoAdapter.getItemCount() - <span class="number">1</span>) &#123;</div><div class="line">            <span class="keyword">if</span> (mFetchItemsTask.getStatus() == AsyncTask.Status.FINISHED) &#123;</div><div class="line">            	<span class="comment">// 下一页加一，在小于最大页数时</span></div><div class="line">            	<span class="comment">// 弹出 Toast 表示正在加载</span></div><div class="line">            	<span class="comment">// 然后打开一个新任务，加载下一页</span></div><div class="line">                mNextPage++;</div><div class="line">                <span class="keyword">if</span> (mNextPage &lt;= MAX_PAGES) &#123;</div><div class="line">                    Toast.makeText(getActivity(), <span class="string">"waiting to load ……"</span>, Toast.LENGTH_SHORT).show();</div><div class="line">                    <span class="comment">// AsyncTask 只能执行一次，所以需要新建</span></div><div class="line">                    mFetchItemsTask = <span class="keyword">new</span> FetchItemsTask();</div><div class="line">                    mFetchItemsTask.execute(mNextPage);</div><div class="line">                &#125; <span class="keyword">else</span> &#123;</div><div class="line">                	<span class="comment">// 滑到最底提示已经到头了</span></div><div class="line">                    Toast.makeText(getActivity(), <span class="string">"This is the end!"</span>, Toast.LENGTH_SHORT).show();</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<h3 id="5-2-2-添加数据并展示"><a href="#5-2-2-添加数据并展示" class="headerlink" title="5.2.2 添加数据并展示"></a>5.2.2 添加数据并展示</h3><p>我在 Adapter 中加入了一个 addData 方法，将新的数据加入到数据集中，然后使用 notifyDataSetChanged 方法更新视图。</p>
<p>然后修改了 setAdapter 方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">setAdapter</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">if</span> (isAdded()) &#123;</div><div class="line">        <span class="keyword">if</span> (mPhotoAdapter == <span class="keyword">null</span>) &#123;</div><div class="line">            mPhotoAdapter = <span class="keyword">new</span> PhotoAdapter(mItems);</div><div class="line">            mPhotoRecyclerView.setAdapter(mPhotoAdapter);</div><div class="line">            mPhotoRecyclerView.addOnScrollListener(onButtomListener);</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            mPhotoAdapter.addData(mItems);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="5-3-动态调整网格列"><a href="#5-3-动态调整网格列" class="headerlink" title="5.3 动态调整网格列"></a>5.3 动态调整网格列</h2><p>使用 OnGlobalLayoutListener 即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">mPhotoRecyclerView.getViewTreeObserver()</div><div class="line">.addOnGlobalLayoutListener(<span class="keyword">new</span> ViewTreeObserver.OnGlobalLayoutListener() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onGlobalLayout</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="comment">// 计算列数，以 1080p 屏幕显示3列为基准</span></div><div class="line">        <span class="keyword">int</span> columns = mPhotoRecyclerView.getWidth() / <span class="number">350</span>;</div><div class="line">        <span class="comment">// 重新设置 LayoutManager、Adapter 和 Listener</span></div><div class="line">        mPhotoRecyclerView.setLayoutManager(<span class="keyword">new</span> GridLayoutManager(getActivity(), columns));</div><div class="line">        mPhotoRecyclerView.setAdapter(mPhotoAdapter);</div><div class="line">        mPhotoRecyclerView.addOnScrollListener(onButtomListener);</div><div class="line">        <span class="comment">// 滚动到之前看到的位置</span></div><div class="line">        mPhotoRecyclerView.getLayoutManager().scrollToPosition(mLastPosition);</div><div class="line">        <span class="comment">//将 GlobalLayoutListener 去掉以避免多次触发</span></div><div class="line">        mPhotoRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(<span class="keyword">this</span>);</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017-02-07-cj0ag5y6q001kifs6872frh9c/" rel="next" title="Android编程权威指南（第二版）学习笔记（二十二）—— 第22章 深入学习 intent 和任务">
                <i class="fa fa-chevron-left"></i> Android编程权威指南（第二版）学习笔记（二十二）—— 第22章 深入学习 intent 和任务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017-02-15-cj0ag5y6w001tifs6pdnqqnhm/" rel="prev" title="Android编程权威指南（第二版）学习笔记（二十四）—— 第24章 Looper、Handler 和 HandlerThread">
                Android编程权威指南（第二版）学习笔记（二十四）—— 第24章 Looper、Handler 和 HandlerThread <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://kniost-comment-github.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
                                
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="kniost" />
          <p class="site-author-name" itemprop="name">kniost</p>
           
              <p class="site-description motion-element" itemprop="description">kniost 的成长与疑惑</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-网络连接基本"><span class="nav-text">1. 网络连接基本</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-线程与主线程"><span class="nav-text">2. 线程与主线程</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-AsyncTask"><span class="nav-text">3. AsyncTask</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-AsyncTask-的生命"><span class="nav-text">3.1 AsyncTask 的生命</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-AsyncTask-的三个参数"><span class="nav-text">3.2 AsyncTask 的三个参数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-1-第一个参数：输入"><span class="nav-text">3.2.1 第一个参数：输入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-2-第二个参数：进度"><span class="nav-text">3.2.2 第二个参数：进度</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-3-第三个参数：结果"><span class="nav-text">3.2.3 第三个参数：结果</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-JSON-数据解析"><span class="nav-text">4. JSON 数据解析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一个例子"><span class="nav-text">一个例子</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-挑战练习"><span class="nav-text">5. 挑战练习</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-使用-Gson-库解析-JSON-数据"><span class="nav-text">5.1 使用 Gson 库解析 JSON 数据</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-1-添加-Gson-依赖"><span class="nav-text">5.1.1 添加 Gson 依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-2-构建对应的-POJO-类"><span class="nav-text">5.1.2 构建对应的 POJO 类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-3-使用-Gson"><span class="nav-text">5.1.3 使用 Gson</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-分页显示"><span class="nav-text">5.2 分页显示</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-1-RecyclerView-onScrollListener"><span class="nav-text">5.2.1 RecyclerView.onScrollListener</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-2-添加数据并展示"><span class="nav-text">5.2.2 添加数据并展示</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-动态调整网格列"><span class="nav-text">5.3 动态调整网格列</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kniost</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'kniost-comment-github';
      var disqus_identifier = '2017-02-11-cj0ag5y6s001nifs6ztgicoai/';

      var disqus_title = "Android编程权威指南（第二版）学习笔记（二十三）—— 第23章 HTTP 与后台任务";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
